//
//  TZTabBar.m
//  wangYiCaiPiao
//
//  Created by mac on 16/1/4.
//  Copyright © 2016年 tz. All rights reserved.
//

#import "TZTabBar.h"
#import "TZButton.h"

@interface TZTabBar ()
@property (nonatomic, strong) UIButton *currentButton;
@end

@implementation TZTabBar

- (void)layoutSubviews {
    [super layoutSubviews];
    //计算frame
    for (int i = 0; i < self.subviews.count; ++i) {
        //获取button
//#warning 注意一下 self.subviews[i]
        UIButton *btn = self.subviews[i];
        CGFloat W = [UIScreen mainScreen].bounds.size.width / 5.0;
        CGFloat H = 49;
        CGFloat X = i * W;
        CGFloat Y = 0;
        btn.frame = CGRectMake(X, Y, W, H);
        
        btn.tag = i; //用来切换控制器
        //初始按钮状态为 selected
        if (i == 0) {
            [self buttonClick:btn];
        }
    }
}
- (void)addButtonImage:(UIImage *)image andButtonSelectedImage:(UIImage *)SelectedImage {
    TZButton *button = [[TZButton alloc] init];
    [button setBackgroundImage:image forState:UIControlStateNormal];
    [button setBackgroundImage:SelectedImage forState:UIControlStateSelected];
    //监听
    [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    //关闭高亮
//    [button setAdjustsImageWhenHighlighted:NO];
    [self addSubview:button];
}

- (void)buttonClick:(UIButton *)button {
    self.currentButton.selected = NO;
    button.selected = YES;
    self.currentButton = button;
//    NSLog(@"%ld",(long)button.tag);
    //判断协议是否被调用
    if ([self.delegate respondsToSelector:@selector(tabBar:andWithSelectedIndex:)]) {
        //执行代理方法
        [self.delegate tabBar:self andWithSelectedIndex:button.tag];
    }
}
@end
